package com.cloudy.impl;

import java.io.IOException;
import java.io.OutputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.cloudy.exception.S3AccessException;
import com.cloudy.security.S3RequestSigner;

public abstract class S3Object {

	public static final String CONTENT_ENCODING = "Content-Encoding";
	public static final String CACHE_CONTROL = "Cache-Control";
	public static final String CONTENT_MD5 = "Content-MD5";
	public static final String CONTENT_DISPOSITION = "Content-Disposition";
	
	private Map<String, List<String>> headers = new HashMap<String, List<String>>();
	private String contentMD5;
	
	public abstract String getContentType();

	public abstract long getContentLength();
	
	protected abstract byte[] getContentAsBytes() throws IOException;
	
	abstract void writeContentToOutPutStream(OutputStream outputStream) throws IOException;
	
	public void setContentMD5(String headerElement) {
		addHeader(headerElement, CONTENT_MD5);
		contentMD5 = headerElement;
	}
	
	public void setContentMD5() throws S3AccessException {
		MessageDigest md;
		try {
			md = MessageDigest.getInstance("MD5");
			byte[] bytes = getContentAsBytes();
			String md5Content =S3RequestSigner.encodeBase64(md.digest(bytes));
			setContentMD5(md5Content);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (IOException e) {
			throw new S3AccessException(e);
		}
	}

	public void addHeader(String headerElement, String key) {
		if(headers.get(key)==null){
			headers.put(key, new ArrayList<String>());
		}
		headers.get(key).add(headerElement);
	}
	
	public Map<String, List<String>> getHeaders(){
		return headers;		
	}

	public String getContentMD5() {
		return contentMD5==null?"":contentMD5;
	}
}